package com.xxxx.server.config.security.component;

import com.xxxx.server.pojo.Menu;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.security.Security;
import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求url分析请求所需角色
 *
 * @author Ding Yi
 */

/**/
//  查询所有路径以及该路径对应的角色，并且根据访问路径和查询到的路径相匹配，并返回访问该路径需要的角色
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IMenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        /*获取请求的url*/
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menus = menuService.getMenusWithRole();
        System.out.println("CustomFilter >>>>>>>>>  请求的地址" + requestUrl);
        System.out.println("menus >>>>>>>>>  " + menus);
        for (Menu menu : menus) {
            System.out.println(menu.getUrl());
            /*判断请求url与菜单角色是否匹配*/
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                System.out.println("menu >>>>>>>>>>>>>>>>" + menu);
                String[] strings = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(strings);
            }
        }
        System.out.println("CustomFilter >>>>>>>>>  请求的地址" + requestUrl);

        /*没匹配的url默认登录即可访问*/
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
